﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel.Web;
using System.Web;
using DHQGHN.DAL.BO;

namespace DHQGHN.Services
{
    public class RoleChecking
    {
        public static bool IsRight(IncomingWebRequestContext request)
        {
            WebHeaderCollection headers = request.Headers;
            string userName = headers["userName"];
            string password = headers["password"];
            string method = headers["methodName"];
            List<string> methodList = new List<string>();
            bool result = false;
            if(IsValid(userName, password))
            {
                methodList = GetListMethod(userName);
                if (methodList.Contains(method))
                {
                    result = true;
                }
            }

            return result;
        }

        public static bool CanAccess(WebHeaderCollection headers)
        {
            string userName = headers["userName"];
            string password = headers["password"];
            string method = headers["methodName"];
            List<string> methodList = new List<string>();
            bool result = false;
            if (IsValid(userName, password))
            {
                methodList = GetListMethod(userName);
                if (methodList.Contains(method))
                {
                    result = true;
                }
            }

            return result;
        }

        private static bool IsValid(string userName, string password)
        {
            ServiceUsersBO obj = new ServiceUsersBO();

            return obj.CheckLogin(userName, password);
        }

        private static List<string> GetListMethod(string userName)
        {
            ServiceUsersBO obj = new ServiceUsersBO();
            List<string> methodList = new List<string>();
            List<DAL.Models.ServiceMethodModel> serviceMethodList = obj.GetServiceMethodByUserName(userName);
            int len = serviceMethodList.Count;
            for(int i = 0; i < len;i++)
            {
                methodList.Add(serviceMethodList[i].MethodName);
            }

            return methodList;
        }

        public static void ThrowUnauthorizedException()
        {
            OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
            response.StatusCode = HttpStatusCode.Unauthorized;
            response.StatusDescription = "You are not authorized.";
            HttpContext.Current.Response.Write("You are not authorized.");
        }
    }
}